<?php

$data['errors'] = array();

if (isset($_SESSION['isLogged']) && $_SESSION['isLogged'] == true) {
    header('Location: index.php');
    exit();
}
if (isset($_POST['username']) && isset($_POST['password'])) {
    $username = trim($_POST['username']);
    $password = trim($_POST['password']);
    $username_esc = mysqli_real_escape_string($connection, $username);
    $password_esc = mysqli_real_escape_string($connection, $password);

    $sql = 'SELECT * FROM users WHERE (username = "' . $username_esc .
            '" AND password = "' . $password_esc . '")';
    $query = mysqli_query($connection, $sql);

    if (mysqli_num_rows($query) == 1) {
        $row = mysqli_fetch_assoc($query);
        $_SESSION['isLogged'] = true;
        $_SESSION['username'] = $username;
        $_SESSION['user_id'] = $row['user_id'];
        header('Location: index.php');
        exit();
    } else {
        $data['errors'][] = 'Невалидно потребителско име или парола';
    }
}

$data['title'] = 'Вход';
render($data, 'templates/login_public.php');